; (function () {
  const mainEle = $("#main")  //main元素
  let smallPlaneArr = []    //敌机数组
  const bulletArr = [] //玩家子弹数组
  const player = new PlayerPlane("./images/myplane.gif", 190, 728, 25)  //玩家飞机
  let leftBtnState = false    // 玩家飞机移动状态
  let rightBtnState = false
  let upBtnState = false
  let downBtnState = false
  let spaceBtnState = false  // 玩家飞机开火状态
  let killPlane = $('#Score') //杀敌数量
  let gameStartState = false
  const gameMusic = $('#gameMusic')
  const gameMusic2 = $('#gameMusic2')
  const bullet = $('#bullet')
  const enemy2Down = $('#enemy2Down')

  // 创建敌方小飞机（构建函数）
  function SmallPlane(imgSrc, x, y, speed) {
    // init
    this.imgNode = $create('img') //每个敌方小飞机的图像元素
    this.imgNode.src = imgSrc
    this.imgNode.style.height = "70px"
    this.imgNode.id = "SmallPlane"
    this.imgNode.style.position = "absolute"
    this.imgNode.style.left = x + "px"
    this.imgNode.style.top = y + "px"
    this.speed = speed
    mainEle.appendChild(this.imgNode)
    // 移动
    this.move = function () {
      this.imgNode.style.top = parseInt(this.imgNode.style.top) + this.speed + "px"
    }
    // 摧毁（还得移除数组）
    this.blast = function () {
      mainEle.removeChild(this.imgNode)
    }
  }

  // 创建玩家飞机(构建函数)
  function PlayerPlane(imgSrc, x, y, speed) {
    SmallPlane.call(this, imgSrc, x, y, speed)
    this.imgNode.style.height = ""
    this.imgNode.id = "myPlane"
    // 玩家飞机移动方法
    this.moveLeft = function () {
      if (gameStartState == false) return
      if (parseInt(this.imgNode.style.left) <= -100) {
        this.imgNode.style.left = "480px"
      }
      this.imgNode.style.left = parseInt(this.imgNode.style.left) - this.speed + "px"
    }
    this.moveRight = function () {
      if (gameStartState == false) return
      if (parseInt(this.imgNode.style.left) >= 480) {
        this.imgNode.style.left = "-100px"
      }
      this.imgNode.style.left = parseInt(this.imgNode.style.left) + this.speed + "px"
    }
    this.moveUp = function () {
      if (gameStartState == false) return
      console.log(parseInt(this.imgNode.style.top));
      if (parseInt(this.imgNode.style.top) <= 10) {
        return
      }
      this.imgNode.style.top = parseInt(this.imgNode.style.top) - this.speed + "px"
    }
    this.moveDown = function () {
      if (gameStartState == false) return
      if (parseInt(this.imgNode.style.top) >= 728) {
        return
      }
      this.imgNode.style.top = parseInt(this.imgNode.style.top) + this.speed + "px"
    }
    // 发射子弹
    this.shoot = function () {
      if (gameStartState == false) return
      var shootLeft = parseInt(this.imgNode.style.left) + 45
      var shootTop = parseInt(this.imgNode.style.top) - 20
      var newBullet = new Bullet("./images/bullet1.png", shootLeft, shootTop, 50)
      bulletArr.push(newBullet)
      console.log(bulletArr);
    }
  }

  // 创建子弹(构建函数)
  function Bullet(imgSrc, x, y, speed) {
    SmallPlane.call(this, imgSrc, x, y, speed)
    this.imgNode.style.height = ""
    this.move = function () {
      this.imgNode.style.top = parseInt(this.imgNode.style.top) - this.speed + "px"
    }
  }

  // 生成敌方小飞机实例（定时器重复执行）
  function createSmallPlane() {
    // x:411 y:763
    const smallPlane = new SmallPlane("./images/enemy1.png", parseInt(Math.random() * 411), -parseInt(Math.random() * 100 + 89), randomNum(5, 20))
    smallPlaneArr.push(smallPlane)
  }

  // 生成敌方小飞机后执行move方法（定时器重复执行）
  function smallPlaneMove() {
    for (let i = 0; i < smallPlaneArr.length; i++) {
      smallPlaneArr[i].move()
      // 飞机移出范围后删除ele元素和arr数组
      if (parseInt(smallPlaneArr[i].imgNode.style.top) >= 852) {
        console.log('执行了');
        mainEle.removeChild(smallPlaneArr[i].imgNode)
        smallPlaneArr.splice(i, 1)
      }
    }
  }

  // 判断按键状态控制玩家飞机移动（需要用定时器重复执行）
  function playerPlaneMove() {
    if (leftBtnState) {
      player.moveLeft()
    }
    if (rightBtnState) {
      player.moveRight()
    }
    if (upBtnState) {
      player.moveUp()
    }
    if (downBtnState) {
      player.moveDown()
    }
  }

  // 判断玩家飞机发射子弹状态（需要用定时器重复执行）
  function shootMove() {
    if (spaceBtnState) {
      if (gameStartState == false) return
      bullet.play()
      player.shoot()
    }
  }

  // 玩家飞机子弹生成后执行move方法（定时器重复执行）
  function bulletMove() {
    for (let i = 0; i < bulletArr.length; i++) {
      bulletArr[i].move()
      // 子弹移出范围后删除ele元素和arr数组
      if (parseInt(bulletArr[i].imgNode.style.top) <= 0) {
        mainEle.removeChild(bulletArr[i].imgNode)
        bulletArr.splice(i, 1)
      }
    }
  }

  // 判断子弹碰撞（定时器重复执行）
  function carashCheck() {
    // 敌方飞机
    smallPlaneArr.forEach((item, index) => {
      // 子弹
      bulletArr.forEach((item2, index2) => {
        var bulletLeft = parseInt(item2.imgNode.style.left)  // 子弹距离左边距离
        var bulletTop = parseInt(item2.imgNode.style.top)  // 子弹距离顶部距离
        var palneLeft = parseInt(item.imgNode.style.left)  // 小飞机距离顶部距离
        var palneTop = parseInt(item.imgNode.style.top)  // 小飞机距离顶部距离
        // 10为优化边缘爆炸
        if (bulletLeft >= palneLeft - 10 && bulletLeft <= palneLeft + 54 + 10 && bulletTop >= palneTop && bulletTop <= palneTop + 70) {
          enemy2Down.cloneNode().play()
          // 碰撞之后移除子弹元素、数组
          mainEle.removeChild(item2.imgNode)
          bulletArr.splice(index2, 1)
          // 敌机爆炸（移除元素、数组）
          smallPlaneBlast(item, index)
          // 加分
          killPlane.innerHTML = parseInt(killPlane.innerHTML) + 10
        }
      })
    })
  }

  // 敌军爆炸
  function smallPlaneBlast(item, index) {
    smallPlaneArr.splice(index, 1)
    item.imgNode.src = "./images/enemy1_down1.png"
    setTimeout(() => {
      item.imgNode.src = "./images/enemy1_down2.png"
      setTimeout(() => {
        item.imgNode.src = "./images/enemy1_down3.png"
        setTimeout(() => {
          item.imgNode.src = "./images/enemy1_down4.png"
          setTimeout(() => {
            mainEle.removeChild(item.imgNode)
          }, 100);
        }, 30);
      }, 30);
    }, 30);
  }

  // 监听按键（玩家移动与发射子弹）
  window.onkeydown = function (event) {
    console.log(event);
    if (event.keyCode == 37 || event.keyCode == 65) {
      leftBtnState = true
    }
    if (event.keyCode == 38 || event.keyCode == 87) {
      upBtnState = true
    }
    if (event.keyCode == 39 || event.keyCode == 68) {
      rightBtnState = true
    }
    if (event.keyCode == 40 || event.keyCode == 83) {
      downBtnState = true
    }
    // if (event.keyCode == 32 || event.keyCode == 74) {
    //   spaceBtnState = true
    // }
    if (event.keyCode == 13) {
      (function () {
        smallPlaneArr = []
        const temp = document.querySelectorAll('#SmallPlane');
        temp.forEach((item) => {
          mainEle.removeChild(item)
        })
        $('#titleScore').style.display = "block"
        $('#start').style.display = "none"
        gameStartState = true
        gameMusic.pause()
        gameMusic2.play()
      })()
    }
  }

  //松开按键
  window.onkeyup = function (event) {
    if (event.keyCode == 37 || event.keyCode == 65) {
      leftBtnState = false
    }
    if (event.keyCode == 38 || event.keyCode == 87) {
      upBtnState = false
    }
    if (event.keyCode == 39 || event.keyCode == 68) {
      rightBtnState = false
    }
    if (event.keyCode == 40 || event.keyCode == 83) {
      downBtnState = false
    }
    // if (event.keyCode == 32 || event.keyCode == 74) {
    //   spaceBtnState = false
    // }
  }

  // init
  gameMusic.play()

  // 开始游戏
  $('#start').onclick = function () {
    smallPlaneArr = []
    const temp = document.querySelectorAll('#SmallPlane');
    temp.forEach((item) => {
      mainEle.removeChild(item)
    })
    $('#titleScore').style.display = "block"
    $('#start').style.display = "none"
    gameStartState = true
    spaceBtnState = true
    gameMusic.pause()
    gameMusic2.play()
  }

  // 定时器
  setInterval(() => {
    createSmallPlane()    // 敌方飞机生成定时器
  }, randomNum(200, 1000));

  setInterval(() => {
    smallPlaneMove();    // 敌方飞机移动定时器
    playerPlaneMove();   // 玩家移动状态定时器（移动频率）
    bulletMove();  // 子弹移动定时器
  }, 50);

  setInterval(() => {
    shootMove()  //发射子弹状态定时器（子弹频率）
  }, 150)

  setInterval(() => {
    carashCheck();  //检测子弹撞击定时器（子弹频率）
  }, 10)

})()






